<?php

namespace console\controllers;

use Yii;
use common\models\shop\ShopOrder;
use common\logics\CommissionLogic;
use common\models\spread\SpreadAttract;
use common\models\BaseUser;
use yii\helpers\Console;
use common\logics\SpreadLogic;

/**
 * Manages application migrations.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class SpreadController extends \yii\console\Controller {

    const BATCH_SIZE = 20;

    /**
     * @view update.php
     * @return mixed
     */
    public function actionTest($id) {
        $data = SpreadLogic::joinBranch('', $id);
        Console::output(print_r($data, true));
    }

    /**
     * @view update.php
     * @return mixed
     */
    public function actionIndex() {
        $query = SpreadAttract::find()->active()->andWhere([
            'branch_user_id' => 0
        ])->orderBy([
            'created_at' => SORT_ASC
        ]);
        $count = $query->count();
        $i = 0;
        if (!$count) {
            return;
        }
        $size = ceil($count / static::BATCH_SIZE);
        Console::startProgress($i, $size, 'Counting objects: ', false);
        foreach ($query->batch(static::BATCH_SIZE) as $rows) {
            $this->transData($rows);
            Console::updateProgress(++$i, $size);
        }
        Console::endProgress("update done." . PHP_EOL);
    }

    protected function transData($data) {
        foreach ($data as $spread) {
            $user = null;
            if ($spread->token && $spread->token->user_id) {
                $user = BaseUser::findOne($spread->token->user_id);
            } elseif ($spread->connect && $spread->connect->user_id) {
                $user = BaseUser::findOne($spread->connect->user_id);
            } elseif ($spread->mobile) {
                $user = BaseUser::findByMobile($spread->mobile);
            }
            if (!$user) {
                continue;
            }
            $mobile = '';
            if ($user->mobile_hash) {
                $mobile = $user->decryptMobile(false);
            }
            $spread->branch_user_id = $user->id;
            if ($spread->save()) {
                $string = $user->id . ' will bind to ' . $spread->user_id;
                Console::output($string);
                Console::output($mobile);
                SpreadLogic::joinBranch($mobile, $user->id);
            }
        }
    }

}
